<template>
  <app-content class="h-panel">
    <div class="h-panel-bar"><span class="h-panel-title">账套管理</span></div>
    <div class="margin-top margin-left">
      <Button color="primary" @click="showForm=true" :style="btnStyle">新建账套</Button>
      <Button @click="loadList" style="margin-left:5px">刷新</Button>&nbsp;&nbsp;
      当前账套数量：{{datas.length}}个，总共可以创建账套数量：{{limitNum}}个
    </div>
    <div class="h-panel-body">
      <Table :datas="datas" :border="true">
        <TableItem title="操作" :width="200" align="center">
          <div class="actions" slot-scope="{data}">
            <span @click="setDefault(data)" :style="fontStyle">设为当前</span>
            <span @click="edit(data)" :style="fontStyle">编辑</span>
            <span @click="remove(data)" v-if="User.role === 'Manager'" :style="fontStyle">删除</span>
          </div>
        </TableItem>
        <TableItem title="单位名称" prop="companyName">
          <template slot-scope="{data}">
            <span class="h-tag h-tag-bg-primary" style="margin-left:5px" v-if="data.isDefault" :style="btnStyle">当前</span>
          </template>
        </TableItem>
        <TableItem title="当前记账年月" prop="currentAccountDate" :width="200" :format="dateFormat"></TableItem>
        <TableItem title="账套启用年月" prop="enableDateStr" :width="200" :format="dateFormat"></TableItem>
        <TableItem title="会计准则" prop="accountingStandards" dict="accountingStandards" :width="200"></TableItem>
        <TableItem title="凭证是否需要审核" prop="voucherReviewed" dict="enableRadios" :width="200"></TableItem>
      </Table>
    </div>
    <Modal v-model="showForm" v-bind="{closeOnMask: false, hasCloseIcon: true}">
      <div slot="header">创建账套</div>
      <Form ref="form" v-width="800" mode="twocolumn" :labelWidth="150" :model="form" :rules="validationRules">
        <FormItem label="单位名称:" prop="companyName">
          <input type="text" v-model="form.companyName">
        </FormItem>
        <FormItem label="账套启用年月:" prop="enableDateStr">
          <DatePicker type="month" v-model="form.enableDateStr" :disabled="used" format="YYYY-MM"/>
        </FormItem>
        <FormItem label="统一社会信用代码:">
          <input type="text" v-model="form.creditCode">
        </FormItem>
        <FormItem label="会计准则:" prop="accountingStandards">
          <Radio v-model="form.accountingStandards" dict="accountingStandards" :disabled="!!form.id"></Radio>
        </FormItem>
        <FormItem label="单位所在地:">
          <CategoryPicker ref="CategoryPicker" :option="pickerOption" type="key" showAllLevels v-model="form.address"></CategoryPicker>
        </FormItem>
        <!--	<FormItem label="固定资产模块:" prop="fixedAssetModule">
            <Radio v-model="form.fixedAssetModule" dict="enableRadios"></Radio>
          </FormItem>-->
        <FormItem label="行业:">
          <Select v-model="form.industry" dict="industry"></Select>
        </FormItem>
        <!--	<FormItem label="是否启用出纳模块:" prop="cashierModule">
            <Radio v-model="form.cashierModule" dict="enableRadios"></Radio>
          </FormItem>-->
        <FormItem label="增值税种类:" prop="vatType">
          <Radio v-model="form.vatType" dict="vatRadios"></Radio>
        </FormItem>
        <FormItem label="凭证是否需要审核:" prop="voucherReviewed">
          <Radio v-model="form.voucherReviewed" dict="needRadios"></Radio>
        </FormItem>
      </Form>
      <div class="text-center">
        <Button color="primary" @click="submit" :loading="loading" :style="btnStyle">{{form.id?'更新':'创建'}}账套</Button>
        <Button @click="showForm=false">取消</Button>
      </div>
    </Modal>
    <Modal v-model="showModal" hasCloseIcon hasDivider>
      <div slot="header">删除账套</div>
      <div>
        <div>您正在删除账套：<b>{{rmData.companyName}}</b>
          <br>友情提醒：删除账套会同时删除与账套相关的凭证、科目、结账等信息
          <br>为保障数据安全，需要输入登录密码验证身份</div>
        <Row type="flex" :space="10" style="margin: 10px 0 10px 0">
          <Cell><input v-model="password" type="password" placeholder="请输入登录密码"></Cell>
        </Row>
      </div>
      <div class="text-center">
        <Button color="red" @click="doRemove" :loading="loading">删除</Button>
        <Button @click="showModal=false" style="margin-left: 20px">取消</Button>
      </div>
    </Modal>
  </app-content>
</template>

<script>
  import {getTotalData} from '../../util/js/district';
  import moment from 'moment';
  import {mapState} from 'vuex';
  import Common from '../../util/api/common'
  import md5 from 'md5'
  import Vue from 'vue'
  import { DEFAULT_COLOR } from '@/store/mutation-types'
  import { updateTheme } from '@comp/tools/setting'

  const emptyForm = {
    "accountingStandards": "0",
    "address": null,
    "companyName": "",
    "creditCode": "",
    "enableDate": null,
    "fixedAssetModule": "0",
    "cashierModule": "0",
    "voucherReviewed": "0",
    "industry": "",
    "vatType": "0"
  };

  export default {
    name: 'AccountSets',
    data() {
      return {
        datas: [],
        limitNum: 0,
        pickerOption: {
          keyName: 'id',
          titleName: 'title',
          dataMode: 'list',
          parentName: 'parentId',
          datas: getTotalData()
        },
        form: Object.assign({}, emptyForm),
        validationRules: {
          required: ["companyName", "enableDateStr", "accountingStandards", "fixed_asset_module", "cashier_module", "voucherReviewed", "vatType"]
        },
        showModal: false,
        rmData: {},
        password: '',
        showForm: false,
        used: false,
        loading: false,
        btnStyle: { background: '', borderColor: ''},
        fontStyle: { color: ''},
      };
    },
    watch: {
      showForm(val) {
        if (!val) {
          this.reset();
        }
      }
    },
    computed: {
      ...mapState(["User"])
    },
    mounted () {
      this.primaryColor = Vue.ls.get(DEFAULT_COLOR)
      updateTheme(this.primaryColor)
      this.btnStyle.background = this.primaryColor
      this.btnStyle.borderColor = this.primaryColor
      this.fontStyle.color = this.primaryColor
      this.loadList()
      this.getLimitNum()
    },
    methods: {
      loadList() {
        this.$api.setting.accountSets.list().then(({data}) => {
          this.datas = data || [];
        })
      },
      getLimitNum() {
        this.$api.setting.accountSets.getLimitNum().then(({data}) => {
          this.limitNum = data || 0;
        })
      },
      submit() {
        let validResult = this.$refs.form.valid();
        if (validResult.result) {
          this.loading = true;
          this.form.enableDate = moment(this.form.enableDateStr).format("YYYY-MM-DD");
          this.$api.setting.accountSets[this.form.id ? 'update' : 'save'](this.form).then(() => {
            this.$store.dispatch('init');
            this.loadList();
            this.showForm = false;
            this.loading = false;
          }).catch(() => {
            this.loading = false;
          })
        }
      },
      reset() {
        this.form = Object.assign({}, emptyForm);
        this.used = false;
      },
      dateFormat(val) {
        return val ? moment(val).format("YYYY年MM月") : '';
      },
      remove(data) {
        this.showModal = true;
        this.password = ''
        this.rmData = data;
      },
      doRemove() {
        if(this.password) {
          this.$Confirm("确认删除?").then(() => {
            this.$api.setting.accountSets.delete(this.rmData.id, md5(this.password)).then(() => {
              this.loadList();
              this.$store.dispatch('init');
              this.showModal = false;
              this.rmData = {};
              this.password = '';
            })
          })
        } else {
          this.$Message("请输入登录密码！");
        }
      },
      setDefault(row) {
        Common.changeAccountSets(row.id).then(({data}) => {
          this.loadList()
        })
      },
      edit(row) {
        this.$api.setting.accountSets.checkUse(row.id).then(({data}) => {
          this.used = data;
          this.form = Object.assign({}, row);
          this.showForm = true;
        })
      }
    }
  };
</script>

<style scoped lang="less">
  .h-panel-bar {
    padding: 10px 20px;
  }
</style>